/**
 * 2018年11月22日上午11:03:46
 * @author 谢进财
 */
package com.baihang.project.ds.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baihang.framework.dao.ModelToSql;
import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.dao.LouDongDao;
import com.baihang.project.ds.model.LouDongModel;
import com.baihang.project.ds.model.RenChouModel;

/**
 * 楼栋服务
 *
 */
@Service("loudong")
public class LouDongService extends BaseService  {
	@Autowired
	public LouDongDao dao;
	
	public String getTree() {
		List<Record> list= dao.queryForRecordList("select D_ID,D_BanName,D_Type,D_Order,D_ID as id,D_BanName as text from bans order by D_Order");
		String loudongs = JsonKit.listToJson(list, 1);
		StringBuilder sb = new StringBuilder("[{");
		sb.append("\"text\":"+"\"全部楼栋\",");
		sb.append("\"children\":"+loudongs);
		sb.append("}]");
		//String tree="[{  \"text\": \"在线选房\",\"children\":[{\"D_ID\":110,\"D_BanName\":\"1号楼\",\"D_Type\":\"20000\",\"D_Order\":1,\"id\":\"110\",\"text\":\"1号楼\"},{\"D_ID\":111,\"D_BanName\":\"2号楼\",\"D_Type\":\"20000\",\"D_Order\":2,\"id\":\"111\",\"text\":\"2号楼\"}]}]";
		return sb.toString();
	}
	
	public boolean checkExistLouDong(String name) {
		String sql = String.format("select count(*) from bans where D_BanName='%s'", name);
		System.err.println(sql);
		int count = dao.queryForInt(sql);
		boolean result=count>0?false:true;
		return result;
	}
	
	public boolean addLouDong(LouDongModel model) {		
		int count = dao.save(ModelToSql.modelToSaveSql(model));
		boolean result=count>0?true:false;
		return result;
	}
	
	public boolean saveLouDong(LouDongModel model) {		
		int count = dao.update(ModelToSql.modelToUpdateSql2(model));
		dao.update(String.format("update room set D_BanName='%s' where BanID=%d", model.getBanName(),model.getID()));
		boolean result=count>0?true:false;
		return result;
	} 
	@Transactional
	public boolean deleteLouDong(int  id) {	
		int delRoom = dao.delete(String.format("delete from room where BanID=%d", id));
		int count = dao.delete(String.format("delete from bans where D_ID=%d", id));
		boolean result=count>0?true:false;
		return result;
	} 
	
	public List<RenChouModel> getRenChou(){
		List<Record> list = dao.queryForRecordList("select * from t_renchou");
		List<RenChouModel> list2 = new ArrayList<RenChouModel>();
		if(list.size()>0) {
			for(Record rec:list) {
				RenChouModel model = new RenChouModel();
				model.setId(rec.getInt("id"));
				model.setName(rec.getStr("name"));
				model.setMoney(rec.getStr("money"));
				list2.add(model);
			}
		}
		return list2;
	}
	
	//获得最大顺序值
	public int getMaxOrder() {
		int maxOrder = dao.queryForInt("select max(D_Order) from Bans");
		return maxOrder+1;
	}
	
}
